package nix.jaxp;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class TestSax {

	/**
	 * @param args
	 * @throws Exception
	 * @throws
	 */
	public static void main(String[] args) throws Exception {

		// test1();

		test2();
	}

	public static void test1() throws Exception {
		// 创建解析器工厂实例
		SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
		// 创建解析器实例
		SAXParser saxParser = saxParserFactory.newSAXParser();
		// 解析xml（xml路径，事件处理器）
		saxParser.parse("src/nix/jaxp/person.xml", new MyDefaultHandler1());
	}

	public static void test2() throws Exception {
		// 创建解析器工厂实例
		SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
		// 创建解析器实例
		SAXParser saxParser = saxParserFactory.newSAXParser();
		// 解析xml（xml路径，事件处理器）
		saxParser.parse("src/nix/jaxp/person.xml", new MyDefaultHandler2());
	}

}

class MyDefaultHandler1 extends DefaultHandler {

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		System.out.print("<" + qName + ">");
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		System.out.print(new String(ch, start, length));
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		System.out.print("</" + qName + ">");
	}
}

class MyDefaultHandler2 extends DefaultHandler {

	boolean flag = false;
	int index = 0;

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if ("name".equals(qName)) {
			flag = true;
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		if (flag == true && index == 0) {
			System.out.println(new String(ch, start, length));
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if ("name".equals(qName)) {
			flag = false;
			index++;
		}
	}
}